#
# Copyright (c) 2023 supercell
#
# SPDX-License-Identifier: BSD-3-Clause
#

require "./link_syntax"

module Luce
  # Matches images like `![alternate text](url "optional title")` and
  # `![alternate text][lable]`.
  class ImageSyntax < LinkSyntax
    def initialize(link_resolver : Resolver? = nil)
      super(link_resolver: link_resolver, pattern: %q(!\[), start_character: Charcode::EXCLAMATION)
    end

    private def create_node(destination : String, title : String?,
                            get_children : Proc(Array(Node))) : Element
      element = Element.empty("img")
      children = get_children.call
      element.attributes["src"] = Luce.normalize_link_destination(Luce.escape_punctuation(destination))
      element.attributes["alt"] = children.map do |node|
        # See https://spec.commonmark.org/0.30/#image-description.
        # An image description may contain links. Fetch text from the alt
        # attribute if this nested link is an image.
        if node.is_a?(Element) && node.tag == "img"
          node.attributes["alt"]
        else
          node.text_content
        end
      end.join
      if !title.nil? && !title.empty?
        element.attributes["title"] = Luce.normalize_link_title(title)
      end
      element
    end
  end
end
